import { memo, useState, useEffect } from 'react'
import { Layout, Input, theme, Space, Tooltip, Typography, Dropdown, Button, Spin, Empty, Modal, message } from 'antd';
import { EllipsisOutlined } from '@ant-design/icons';
import { getDocListOfKnowledgeBase, getDocDetailsByDocId, removeDocFromKnowledgeBase } from '../api';
import { useMessage } from '@/hooks/useMessage';
import { useDocExport } from '@/hooks/useDocExport'; // 导入导出 Hook
import { useLocation } from 'react-router-dom';
import styles from './index.module.less';

const { Sider } = Layout;
const { Search } = Input;
const { Title, Text } = Typography;

const menuItems = [
    { key: 'exportWord', label: '导出Word' },
    { key: 'exportPdf', label: '导出PDF' },
    { key: 'delete', label: '移除', danger: true },
];

const DocDetailSide = ({ knowledgeBaseId, docId, onDocSelect, knowledgeBaseName, onDocListLoaded, 
     refreshKey }) => {
    const {
        token: { colorBgContainer },
    } = theme.useToken();
    const [collapsed, setCollapsed] = useState(false);
    const [docList, setDocList] = useState([]);
    const [loading, setLoading] = useState(false);
    const { error, success, contextHolder } = useMessage();
    const location = useLocation();
    
    // 使用导出 Hook
    const { exportLoading, exportSingleDoc, exportSingleDocToPdf } = useDocExport();

    useEffect(() => {
        fetchDocList();
    }, [knowledgeBaseId, refreshKey]);

    // 获取知识库下的文档列表
    const fetchDocList = async (afterFetch) => {
        if (!knowledgeBaseId) return;
        try {
            setLoading(true);
            const res = await getDocListOfKnowledgeBase(knowledgeBaseId);
            if (res && res.code === 200 && Array.isArray(res.data)) {
                const formattedDocs = res.data.map(doc => ({
                    id: doc.docId,
                    title: doc.docName,
                    owner: doc.username,
                    updateTime: doc.updateTime
                }));
                setDocList(formattedDocs);
                if (onDocListLoaded) onDocListLoaded(formattedDocs);
                if (typeof afterFetch === 'function') afterFetch(formattedDocs);
            } else {
                setDocList([]);
                if (onDocListLoaded) onDocListLoaded([]);
                if (typeof afterFetch === 'function') afterFetch([]);
            }
        } catch (err) {
            setDocList([]);
            if (onDocListLoaded) onDocListLoaded([]);
            if (typeof afterFetch === 'function') afterFetch([]);
        } finally {
            setLoading(false);
        }
    };

    const handleAddExistingSuccess = () => {
        setAddExistingModalVisible(false);
    };

    // 搜索事件处理
    const onSearch = (value) => {
        console.log('搜索:', value);
        // 这里可以实现文档搜索功能
    }

    // 文档行点击事件
    const handleDocumentClick = async (doc) => {
        try {
            const res = await getDocDetailsByDocId(doc.id);
            if (res && res.code === 200 && res.data) {
                // 假设后端返回结构为 { docName, docId, content, permission, ... }
                onDocSelect({
                    id: res.data.docId,
                    title: res.data.docName,
                    content: res.data.docContent,
                    permission: res.data.docPermission, // 假如有权限字段
                    // ...可扩展其它字段
                });
            }
        } catch (e) {
            // 可选：错误提示
        }
    };

    // 导出文档功能
    const handleExportDoc = async (doc) => {
        try {
            const success = await exportSingleDoc(doc.id, doc.title);
            if (success) {
                message.success(`文档 "${doc.title}" 导出成功`);
            }
        } catch (error) {
            console.error('导出文档失败:', error);
        }
    };

    // 导出PDF
    const handleExportDocPdf = async (doc) => {
        try {
            const success = await exportSingleDocToPdf(doc.id, doc.title);
            if (success) {
                message.success(`文档 "${doc.title}" PDF导出成功`);
            }
        } catch (error) {
            console.error('导出PDF失败:', error);
        }
    };

    // 移除文档功能
    const handleRemoveDoc = async (doc) => {
        try {
            const res = await removeDocFromKnowledgeBase({
                knowledgeBaseId,
                docIdList: [doc.id]
            });
            if (res && res.code === 200) {
                message.success('文档已移出知识库');
                // 重新获取文档列表，并自动选中第一条
                fetchDocList((newList) => {
                    if (newList.length > 0) {
                        onDocSelect(newList[0]);
                    } else {
                        onDocSelect(null);
                    }
                });
            } else {
                message.error(res?.msg || '移除失败，请重试');
            }
        } catch (err) {
            message.error('移除失败，请重试');
        }
    };

    // 下拉菜单点击事件
    const handleMenuClick = (e, doc) => {
        e.domEvent.stopPropagation(); 
        if (e.key === 'exportWord') {
            handleExportDoc(doc);
        } else if (e.key === 'exportPdf') {
            handleExportDocPdf(doc);
        } else if (e.key === 'delete') {
            handleRemoveDoc(doc);
        }
    };

    // 渲染文档列表
    const renderDocList = () => {
        if (loading) {
            return (
                <div className={styles.loadingContainer}>
                    <Spin size="large" />
                </div>
            );
        }

        if (docList.length === 0) {
            return (
                <div className={styles.emptyContainer}>
                    <Empty description="该知识库暂无文档" />
                </div>
            );
        }

        return (
            <Space direction="vertical" className={styles.docListWrapper}>
                {docList.map(doc => (
                    <div
                        key={doc.id}
                        onClick={() => handleDocumentClick(doc)}
                        className={`${styles.docItem} ${docId === doc.id ? styles.docItemSelected : ''}`}
                    >
                        <span className={styles.docItemTitle}>
                            <Text style={{ display: 'block' }} ellipsis>{doc.title}</Text>
                        </span>
                        <Dropdown 
                            menu={{ 
                                items: menuItems, 
                                onClick: (e) => handleMenuClick(e, doc) 
                            }} 
                            trigger={['click']}
                        >
                            <Button
                                type="text"
                                icon={<EllipsisOutlined />}
                                loading={exportLoading} // 添加加载状态
                                onClick={e => e.stopPropagation()} // 阻止按钮点击触发整行点击事件
                            />
                        </Dropdown>
                    </div>
                ))}
            </Space>
        );
    };

    return (
        <div className={styles.docDetailSide} >
            {contextHolder}
            <Sider
                width={300}
                breakpoint="lg"
                collapsed={collapsed}
                onCollapse={setCollapsed}
                collapsedWidth={0} // 收起时完全隐藏，体验更好
                className={styles.sider}
                style={{
                    background: colorBgContainer,
                }}
            >
                {/* 上部分：搜索框 */}
                <div className={styles.searchSection}>
                    <Search
                        placeholder="请输入要搜索的内容"
                        allowClear
                        onSearch={onSearch}
                    />
                </div>

                {/* 下部分：文档列表 */}
                <div className={styles.docListSection}>
                    <Title level={5} className={styles.docListTitle}>
                        {knowledgeBaseName}-文档列表
                    </Title>
                    {renderDocList()}
                </div>
            </Sider>
        </div>
    );
}

export const MemoDocDetailSide = memo(DocDetailSide)